/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package controller;

import persistence.entites.Type;
import javax.annotation.ManagedBean;
import javax.enterprise.context.SessionScoped;
import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;

@ManagedBean
@SessionScoped
public class TypeController extends Controller {

    private Type type = null;
    private transient DataModel types = null;
    private transient DataModel superTypes = null;
    private String superTypeString = "";

    public TypeController() {
        super();
        refreshTypes();
    }

    private void refreshTypes() {
        superTypes = new ListDataModel();
        types = new ListDataModel();
        types.setWrappedData(connMySQL.getTypeDAO().findAll());
    }

    public String index() {
        refreshTypes();
        type = null;
        return "typelist";
    }

    public String ajouterDetail() {
        type = new Type();
        return "typedetail";
    }

    public String modifierDetail() {
        type = (Type) types.getRowData();
        superTypes.setWrappedData(connMySQL.getTypeDAO().findAllSuperTypes(type.getName()));
        return "typedetail";
    }

    public String add() {
        if (superTypeString.equalsIgnoreCase("aucun")) {
            type.setSuperType(null);
        } else {
            Type nstp = connMySQL.getTypeDAO().findByName(superTypeString);
            nstp.getTypes().add(type);
        }
        connMySQL.getTypeDAO().insert(type);
        return index();
    }

    public String update() {
        Type nstp = null;
        if (superTypeString.equalsIgnoreCase("aucun")) {
            type.setSuperType(nstp);
        } else {
            nstp = connMySQL.getTypeDAO().findByName(superTypeString);
            if (!nstp.equals(type.getSuperType())) {
                type.setSuperType(nstp);
            }
        }

        connMySQL.getTypeDAO().update(type);

        return index();
    }

    public String delete() {
        type = connMySQL.getTypeDAO().findById(((Type) types.getRowData()).getId());
        System.out.println(type.getPois());
        connMySQL.getTypeDAO().delete(type);

        return index();
    }

    /**********************
     ***** Accesseurs *****
     **********************/

    public DataModel getSuperTypes() {
        return superTypes;
    }

    public void setSuperTypes(DataModel superTypes) {
        this.superTypes = superTypes;
    }

    public Type getType() {
        return type;
    }

    public void setType(Type type) {
        this.type = type;
    }

    public DataModel getTypes() {
        return types;
    }

    public void setTypes(DataModel types) {
        this.types = types;
    }

    public String getSuperTypeString() {
        return superTypeString;
    }

    public void setSuperTypeString(String superTypeString) {
        this.superTypeString = superTypeString;
    }
}
